/*
 * logger.c
 *
 *  Created on: Dec 13, 2011
 *      Author: piotrek
 */

#include "logger.h"

static pthread_mutex_t logger_mutex = PTHREAD_MUTEX_INITIALIZER;
struct logger *__logger = NULL;

struct logger* init_logger(int n)
{
	struct logger *logger = malloc( sizeof( struct logger ) );
	logger->size = n;
	logger->n = 0;

	logger->descriptors = malloc( sizeof(int) * n );

	return logger;
}


void add_file_logger(struct logger *logger, char *filename)
{
	int fd = open(filename, O_CREAT | O_APPEND | O_WRONLY, 0644 );

	logger->descriptors[logger->n] = fd;
	logger->n += 1;
}

void add_console_logger(struct logger *logger)
{
	logger->descriptors[logger->n] = STDOUT_FILENO;
	logger->n += 1;
}

void dispose_logger(struct logger *logger)
{
	free(logger->descriptors);
	free(logger);
}

struct logger* get_logger()
{
	pthread_mutex_lock(&logger_mutex);

	if(__logger == NULL)
	{
		__logger = init_logger(2);
		add_console_logger(__logger);
		add_file_logger(__logger, "log.txt");
	}

	pthread_mutex_unlock(&logger_mutex);

	return __logger;
}

void log_msg(const char *filename, int lineno, const char *text)
{
	int i;
	struct logger* logger = get_logger();
	char buf[BUF_SIZE];

	pthread_mutex_lock(&logger_mutex);

	time_t t = time(NULL);
	char time_tmp[100];
	ctime_r(&t, time_tmp);
	time_tmp[ strlen(time_tmp)-1 ] = '\0';

	sprintf(buf, "%s [ %s : %d ] %s\n", time_tmp, filename, lineno, text);

	for(i=0; i<logger->n; i++)
	{
		int fd = logger->descriptors[i];
		int n = write(fd, buf, strlen(buf));

		if( n != strlen(buf) )
			printf("Cannot write to a file");
	}

	pthread_mutex_unlock(&logger_mutex);
}
